#include "MaterialManager.h"

MaterialManager::MaterialManager(TexturesManager *texMan, Shader *vpBasicLight, Shader *fpBasicLight)
{
	this ->vpBasicLight = vpBasicLight;
	this ->fpBasicLight = fpBasicLight;
	this ->texMan = texMan;
}

MaterialManager::~MaterialManager(void)
{
}

void MaterialManager::Load(const char *path, const char *ext)
{
	std::string searchPath = path;
	searchPath += "\\*.";
	searchPath += ext;

	WIN32_FIND_DATA fd;

	HANDLE hfile = FindFirstFile(searchPath.c_str(), &fd);
	if (hfile != INVALID_HANDLE_VALUE)
	{
		BOOL doSearch = true;
		while (doSearch)
		{
			std::string matPath = path;
			matPath += "\\";
			matPath += fd.cFileName;

			MaterialsCollection *matColl = new MaterialsCollection();

			std::ifstream file(matPath.c_str(), std::ios::binary | std::ios::in);
			int matCount;
			file.read((char*)&matCount, sizeof(int));
			for (int i = 0; i < matCount; i++)
			{
				Material *mat = MaterialLoader::LoadFromStream(file, texMan);
				mat ->SetBasicLight(vpBasicLight, fpBasicLight);
				matColl ->Add(mat);
			}

			file.close();

			std::string matFileName = fd.cFileName;
			Add(matFileName.substr(0, matFileName.size() - 4).c_str(), matColl);

			doSearch = FindNextFile(hfile, &fd);
		}

		FindClose(hfile);
	}
}

void MaterialManager::Add(const char *name, MaterialsCollection *res)
{
	materials[name] = res;
}

MaterialsCollection * MaterialManager::Get(const char *name)
{
	std::map<std::string, MaterialsCollection*>::iterator i = materials.find(name);
	if (i == materials.end())
		return NULL;

	return (*i).second;
}

int MaterialManager::GetCount()
{
	return (int)materials.size();
}

void MaterialManager::Get(int i, char *name, MaterialsCollection *&res)
{
	std::map<std::string, MaterialsCollection*>::iterator it = materials.begin();
	while (i--)
		it ++;

	strcpy(name, (*it).first.c_str());
	res = (*it).second;
}
